<?php
declare (strict_types=1);

namespace app\command;

use QL\QueryList;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Region extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('region')
            ->setDescription('生成省市区信息');
    }

    protected function execute(Input $input, Output $output)
    {
        $list = Db::name("region_copy1")->where("level", 3)->where("code", ">=", "659004000000")->order("code asc")->cursor();
        $count = 0;
        foreach ($list as $item) {
            $s_data = $this->getStreet($item);
            Db::name("region_copy1")->insertAll($s_data);
//            sleep(2);
            $count++;
            $output->writeln((string)$count);
        }
        // 指令输出
        $output->writeln('region');
    }

    public function getVillage()
    {
        
    }

    public function getStreet($a_item)
    {
        //街道级数据
        if ($a_item['relative_href']) {
            $q_url = iconv('GBK', 'UTF-8', file_get_contents($a_item['href']));
            $s_data = QueryList::html($q_url)
                ->rules([
                    "name" => ["td:eq(1)", 'text'],
                    "href" => ["td:eq(0)>a", 'href'],
                    "code" => ["td:eq(0)", 'text'],
                    "relative_href" => ["td:eq(0)>a", 'href']
                ])
                ->range(".towntable .towntr")->queryData(function ($val) use($a_item){
                    $val['parent_code'] = $a_item['code'];
                    $val['level'] = 4;
                    $val['path_name'] = $a_item['path_name']."-".$val['name'];
                    $val['path_code'] = $a_item['path_code']."-".$val['code'];
                    $base_url_a = explode("/", $a_item['href']);
                    unset($base_url_a[count($base_url_a)-1]);
                    $val['href'] = implode("/", $base_url_a)."/".$val['href'];
                    return $val;
                });
        } else {
            $s_data = [];
        }
        return $s_data;
    }

    public function getRegion()
    {
        $url = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2020/';
        $html = iconv('GBK', 'UTF-8', file_get_contents($url));
        $data = QueryList::html($html)
            ->rules([
                "name" => ["a", 'text'],
                "href" => ["a", 'href'],
                "relative_href" => ["a", 'href'],
            ])
            ->range(".provincetable .provincetr td")->queryData(function ($val) use ($url) {
                $code = explode(".", $val['href'])[0] . "0000";
                $val['href'] = $url . $val['href'];
                $val['code'] = $code;
                return $val;
            });
        //省份数据
        $province_data = array_filter($data, function ($item) {
            if ($item['name']) {
                return true;
            } else {
                return false;
            }
        });
        foreach ($province_data as $k => $p_item) {
            //市级数据
            if ($p_item['relative_href']) {
                $q_url = iconv('GBK', 'UTF-8', file_get_contents($p_item['href']));
                $c_data = QueryList::html($q_url)
                    ->rules([
                        "name" => ["a:eq(1)", 'text'],
                        "href" => ["a:eq(0)", 'href'],
                        "relative_href" => ["a:eq(0)", 'href'],
                        "code" => ["a:eq(0)", 'text'],
                    ])
                    ->range(".citytable .citytr")->queryData(function ($val) use ($url) {
                        $val['href'] = $url . $val['href'];
                        return $val;
                    });
            } else {
                $c_data = [];
            }

            foreach ($c_data as $kk => $c_item) {
                //县级数据
                if ($c_item['relative_href']) {
                    $q_url = iconv('GBK', 'UTF-8', file_get_contents($c_item['href']));
                    $a_data = QueryList::html($q_url)
                        ->rules([
                            "name" => ["td:eq(1)", 'text'],
                            "href" => ["td:eq(0)>a", 'href'],
                            "relative_href" => ["td:eq(0)>a", 'href'],
                            "code" => ["td:eq(0)", 'text'],
                        ])
                        ->range(".countytable .countytr")->queryData(function ($val) use ($p_item) {
                            $url = str_ireplace('.html', '', $p_item['href']) . "/";
                            $val['href'] = $url . $val['href'];
                            return $val;
                        });
                } else {
                    $a_data = [];
                }
                $c_data[$kk]['area'] = $a_data;
            }
            //填充市级数据
            $province_data[$k]['city'] = $c_data;
        }
        file_put_contents("./region.json", json_encode($province_data, JSON_UNESCAPED_UNICODE));
    }

    public function setRegion()
    {
        $ori_data = file_get_contents("./region.json");
        $data = json_decode($ori_data, true);
        foreach ($data as $d) {
            Db::name("region")->insert([
                "code" => $d['code'],
                "name" => $d['name'],
                "href" => $d['href'],
                "relative_href" => $d['relative_href'],
                "level" => 1,
                "parent_code" => "",
                "path_name" => $d['name'],
                "path_code" => $d['code']
            ]);
            //插入市级信息
            $c_data = $d['city'];
            foreach ($c_data as $c) {
                Db::name("region")->insert([
                    "code" => $c['code'],
                    "name" => $c['name'],
                    "href" => $c['href'],
                    "relative_href" => $c['relative_href'],
                    "level" => 2,
                    "parent_code" => $d['code'],
                    "path_name" => $d['name'] . "-" . $c['name'],
                    "path_code" => $d['code'] . "-" . $c['code']
                ]);
                //插入区县信息
                $a_data = $c['area'];
                foreach ($a_data as $a) {
                    Db::name("region")->insert([
                        "code" => $a['code'],
                        "name" => $a['name'],
                        "href" => $a['href'],
                        "relative_href" => $a['relative_href'],
                        "level" => 3,
                        "parent_code" => $c['code'],
                        "path_name" => $d['name'] . "-" . $c['name'] . "-" . $a['name'],
                        "path_code" => $d['code'] . "-" . $c['code'] . "-" . $a['code']
                    ]);
                }
            }
        }
    }
}
